﻿using KwaiXiaoDian.Entity.VO.User;
using KwaiXiaoDian.IService;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using SSharing.Frameworks.NetCore.Common.Consts;
using SSharing.Frameworks.NetCore.Common.Extends;
using SSharing.Frameworks.NetCore.Common.Helpers;
using SSharing.Frameworks.NetCore.Common.Results;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;

namespace KwaiXiaoDian.OpenApi.Controllers
{
    /// <summary>
    /// 用户
    /// </summary>
    [Route("api/[controller]")]
    [ApiController]
    public class UserController : ControllerBase
    {
        private readonly IUserService _userService;

        public UserController(IUserService userService)
        {
            _userService = userService;
        }

        /// <summary>
        /// 获取登录用户信息
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [HttpPost]
        [Route("getloginuserinfo")]
        [Authorize]
        public ActionResult<ApiResult<GetLoginUserInfoResponse>> GetLoginUserInfo()
        {
            var apiResult = new ApiResult<GetLoginUserInfoResponse>();
            GetLoginUserInfoResponse response = new GetLoginUserInfoResponse();

            var userId = User.FindFirst(ClaimTypes.NameIdentifier).Value.ToLong();
            var user = _userService.Get(p => p.Id == userId).First();
            if (user != null)
            {
                response.Id = user.Id;
                response.PhoneNumber = user.PhoneNumber;
                response.Email = user.Email;
                response.NickName = user.NickName;
                response.Role = user.Role;
            }
            apiResult.Data = response;
            apiResult.ErrorCode = ErrorCodeConst.OK;

            return apiResult;
        }

        /// <summary>
        /// 保存帐号信息
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [HttpPost]
        [Route("saveuserinfo")]
        [Authorize]
        public ActionResult<ApiResult> SaveUserInfo(SaveUserInfoRequest request)
        {
            var apiResult = new ApiResult();

            var userId = User.FindFirst(ClaimTypes.NameIdentifier).Value.ToLong();
            var saveUserInfoResult = _userService.SaveUserInfo(request, userId);
            if (saveUserInfoResult.Item1 != true)
            {
                apiResult.ErrorMessage = saveUserInfoResult.Item2;
                return apiResult;
            }
            apiResult.ErrorCode = ErrorCodeConst.OK;

            return apiResult;
        }

        /// <summary>
        /// 获取用户菜单
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [Route("getusermenus")]
        [Authorize]
        public ActionResult<ApiResult<IList<UserMenu>>> GetUserMenus()
        {
            var apiResult = new ApiResult<IList<UserMenu>>();

            var userId = User.FindFirst(ClaimTypes.NameIdentifier).Value.ToLong();
            var role = User.FindFirst(ClaimTypes.Role).Value;
            var userMenus = _userService.GetUserMenus(role);
            apiResult.Data = userMenus;
            apiResult.ErrorCode = ErrorCodeConst.OK;

            return apiResult;
        }

        /// <summary>
        /// 获取用户列表
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [HttpPost]
        [Route("getpagingusers")]
        [Authorize(Roles = "ADMIN")]
        public ActionResult<ApiResult<IPagingResult<UserModel>>> GetPagingUsers(GetPagingUsersRequest request)
        {
            var apiResult = new ApiResult<IPagingResult<UserModel>>();

            //入参校验
            if (request == null)
            {
                request = new GetPagingUsersRequest()
                {
                    Page = 1,
                    Limit = 10
                };
            }
            if (request.Page <= 0)
            {
                request.Page = 1;
            }
            if (request.Limit <= 0)
            {
                request.Limit = 10;
            }

            var pagingUsers = _userService.GetPagingUsers(request);
            apiResult.Data = pagingUsers;
            apiResult.ErrorCode = ErrorCodeConst.OK;

            return apiResult;
        }

        /// <summary>
        /// 新增用户
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [HttpPost]
        [Route("add")]
        [Authorize(Roles = "ADMIN")]
        public ActionResult<ApiResult> Add(AddUserRequest request)
        {
            var apiResult = new ApiResult();
            var now = DateTime.Now;

            //入参校验
            if (request == null)
            {
                request = new AddUserRequest();
            }
            if (request.PhoneNumber.IsNullOrEmpty())
            {
                apiResult.ErrorMessage = "登录手机不能为空！";
                return apiResult;
            }

            var isValidPhoneNumber = RegexHelper.IsMobileNum(request.PhoneNumber);
            if (!isValidPhoneNumber)
            {
                apiResult.ErrorMessage = "登录手机格式不合法！";
                return apiResult;
            }

            if (request.Role.IsNullOrEmpty())
            {
                apiResult.ErrorMessage = "角色不能为空！";
                return apiResult;
            }

            if (!request.Email.IsNullOrEmpty())
            {
                var isValidEmail = RegexHelper.IsEmail(request.Email);
                if (!isValidEmail)
                {
                    apiResult.ErrorMessage = "邮箱格式不合法！";
                    return apiResult;
                }
            }

            var addResult = _userService.Add(request);
            if (addResult.Item1 != true)
            {
                apiResult.ErrorMessage = addResult.Item2;
                return apiResult;
            }
            apiResult.ErrorCode = ErrorCodeConst.OK;

            return apiResult;
        }

        /// <summary>
        /// 修改用户
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [HttpPost]
        [Route("update")]
        [Authorize(Roles = "ADMIN")]
        public ActionResult<ApiResult> Update(UpdateUserRequest request)
        {
            var apiResult = new ApiResult();
            var now = DateTime.Now;

            //入参校验
            if (request == null)
            {
                request = new UpdateUserRequest();
            }
            if (!request.Email.IsNullOrEmpty())
            {
                var isValidEmail = RegexHelper.IsEmail(request.Email);
                if (!isValidEmail)
                {
                    apiResult.ErrorMessage = "邮箱格式不合法！";
                    return apiResult;
                }
            }
            if (request.Role.IsNullOrEmpty())
            {
                apiResult.ErrorMessage = "角色不能为空！";
                return apiResult;
            }

            var updateResult = _userService.Update(request);
            if (updateResult.Item1 != true)
            {
                apiResult.ErrorMessage = updateResult.Item2;
                return apiResult;
            }
            apiResult.ErrorCode = ErrorCodeConst.OK;

            return apiResult;
        }

        /// <summary>
        /// 禁用用户
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [HttpPost]
        [Route("disableuser")]
        [Authorize(Roles = "ADMIN")]
        public ActionResult<ApiResult> DisableUser(DisableUserRequest request)
        {
            var apiResult = new ApiResult();

            //入参校验
            if (request == null)
            {
                request = new DisableUserRequest();
            }
            if (request.IsEnabled.IsNullOrEmpty())
            {
                apiResult.ErrorMessage = "禁用用户状态不能为空！";
                return apiResult;
            }

            var disableUserResult = _userService.DisableUser(request);
            if (disableUserResult.Item1 != true)
            {
                apiResult.ErrorMessage = disableUserResult.Item2;
                return apiResult;
            }
            apiResult.ErrorCode = ErrorCodeConst.OK;

            return apiResult;
        }

        /// <summary>
        /// 重置密码
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [HttpPost]
        [Route("resetpwd")]
        [Authorize(Roles = "ADMIN")]
        public ActionResult<ApiResult> ResetPwd(ResetPwdRequest request)
        {
            var apiResult = new ApiResult();

            //入参校验
            if (request == null)
            {
                request = new ResetPwdRequest();
            }
            if (request.Id<=0)
            {
                apiResult.ErrorMessage = "用户id不能为空！";
                return apiResult;
            }

            var userId = User.FindFirst(ClaimTypes.NameIdentifier).Value.ToLong(0);
            var role = User.FindFirst(ClaimTypes.Role).Value;
            var resetPwdResult = _userService.ResetPwd(request, userId);
            if (resetPwdResult.Item1 != true)
            {
                apiResult.ErrorMessage = resetPwdResult.Item2;
                return apiResult;
            }

            apiResult.ErrorMessage = resetPwdResult.Item2;
            apiResult.ErrorCode = ErrorCodeConst.OK;

            return apiResult;
        }

    }
}
